# -*- coding:utf-8 -*-
import uuid
from datetime import datetime

import torndb

import setting


class TmpImportOrder(object):

    def __init__(self):

        self.db = torndb.Connection(
            host=setting.mysql_host,
            database=setting.mysql_database,
            user=setting.mysql_user,
            password=setting.mysql_password,
            charset='utf8mb4'
        )

    def _get_user_id(self, openid):
        wechat = self.db.get("select user_id from t_wechat where openid=%(openid)s", openid=openid)
        if wechat:
            return wechat.user_id

        return None

    def _create_order(self, user_id=0, products=[]):
        if not user_id:
            print "user_id : {} not exist!".format(user_id)
            return

        id_key = str(uuid.uuid4()).replace("-", "")
        data = {"id": id_key, "user_id": user_id, "total_fee": 0, "status": 1, "out_trade_no": id_key}
        print data
        self.db.execute("insert into t_order (id, user_id, total_fee, paytime, status, create_date, update_date, out_trade_no) values (%(id)s,%(user_id)s,%(total_fee)s,now(),%(status)s,now(),now(),%(out_trade_no)s)", **data)

        for p in products:
            p_id_key = str(uuid.uuid4()).replace("-", "")
            p_data = {"id": p_id_key, "order_id": id_key, "product_id": p["id"], "cnt": p["cnt"], "source": 0}
            print p_data

            self.db.execute("insert into r_order_product (id, order_id, product_id, cnt, source) values (%(id)s,%(order_id)s,%(product_id)s,%(cnt)s,%(source)s)", **p_data)

    def runner(self):

        user_id = self._get_user_id(openid="")
        self._create_order(user_id=user_id, products=[{"id": "", "cnt": 1}, {"id": "", "cnt": 1}])


if __name__ == '__main__':
    print "run start : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    tgn = TmpImportOrder()
    tgn.runner()
    tgn.db.close()
    print "run end : {}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))


